package com.liu.stockmarket.ui.stock.modify

import androidx.lifecycle.*
import com.liu.stockmarket.model.ResponseResult
import com.liu.stockmarket.repository.database.StockRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.math.BigDecimal

class StockModifyViewModel(private val stockRepository: StockRepository) : ViewModel() {

    private val _result = MutableLiveData<ResponseResult<String>>()

    val result: LiveData<ResponseResult<String>> = _result


    fun save(stockId: Long, holdingPrice: BigDecimal, holdingNumber: BigDecimal) {
        viewModelScope.launch(Dispatchers.IO) {
            stockRepository.modifyHoldingPriceAndNumber(stockId, holdingPrice, holdingNumber)
            _result.postValue(ResponseResult.success())
        }

    }

    class StockModifyViewModelFactory(
        private val stockRepository: StockRepository
    ) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return StockModifyViewModel(
                stockRepository
            ) as T
        }

    }
}